package edu.gduf.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import edu.gduf.dao.CourseMapper;
import edu.gduf.dao.SigninMapper;
import edu.gduf.dao.SstMapper;
import edu.gduf.dao.StudentMapper;
import edu.gduf.dto.PageType;
import edu.gduf.dto.QRCodeDTO;
import edu.gduf.dto.SigninSystemResult;
import edu.gduf.dto.SigninVO;
import edu.gduf.dto.SstDTO;
import edu.gduf.entity.Course;
import edu.gduf.entity.Signin;
import edu.gduf.entity.Sst;
import edu.gduf.entity.Teacher;
import edu.gduf.service.SiginService;
import edu.gduf.utils.ExcelUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/signin")
public class SigninController {

	@Autowired
	private SiginService siginService;
	@Autowired
	private SigninMapper signinMapper;

	@Autowired
	private StudentMapper studentMapper;

	@Autowired
	private CourseMapper courseMapper;

	@Autowired
	private SstMapper sstMapper;
	// @ApiOperation(value = "获取签到信息 ")
	// @ApiImplicitParams({
	// @ApiImplicitParam(name = "tId", value = "教师id", required = true, dataType
	// = "Integer"),
	// @ApiImplicitParam(name = "stuId", value = "学生学号", required = false,
	// dataType = "Integer"),
	// @ApiImplicitParam(name = "status", value = "是否签到", required = false,
	// dataType = "Integer") })
	// @RequestMapping(value="/getSignPage",method=RequestMethod.)
	// public List<Signin> getSignInfo(Integer tId, Integer stuId, Integer
	// status) {
	//
	// // return siginService.getSignInfo(pageNum, pageSize, tId,
	// // DateTime.parse(starttime, DateTimeFormat.forPattern("yyyy-MM-dd
	// // HH:mm:ss")).toDate());
	// return null;
	//
	// }

	@ApiOperation(value = "扫描二维码签到,这是Android端的")
	@ApiImplicitParams({ @ApiImplicitParam(name = "tId", value = "教师id", required = true, dataType = "Integer"),

			@ApiImplicitParam(name = "stuId", value = "学生id", required = true, dataType = "int")
 }

	)
	@RequestMapping(value = "/insert", method = RequestMethod.POST)
	public SigninSystemResult insertSignInfo(String stuId, HttpServletRequest request, HttpSession session) {
		SigninSystemResult signinSystemResult = new SigninSystemResult();
		int parseInt = 0;
		try {
			parseInt = Integer.parseInt(stuId);
		} catch (Exception e) {
			signinSystemResult.setSuccess(false);
			signinSystemResult.setMsg("学号不存在.");
			return signinSystemResult;
		}

		QRCodeDTO qrCodeDTO = (QRCodeDTO) session.getAttribute("studentInfo");
		System.out.println("insert===============");
		System.out.println("qrcodedto:" + qrCodeDTO);

		if (qrCodeDTO == null) {
			signinSystemResult.setSuccess(false);
			signinSystemResult.setMsg("等待老师设置签到");
			return signinSystemResult;
		}
		String substring = stuId.substring(0, stuId.length() - 2);
		System.out.println("substring:" + substring);
		int parseInt2 = Integer.parseInt(substring);
		if (parseInt2 != qrCodeDTO.getClassId()) {
			signinSystemResult.setSuccess(false);
			signinSystemResult.setMsg("你所在的班级不是" + qrCodeDTO.getClassId());
			return signinSystemResult;
		}

		if (qrCodeDTO.getHasSignin() == 1) {
			signinSystemResult.setSuccess(false);
			signinSystemResult.setMsg("你的手机已签到了" + qrCodeDTO.getStuId());
			return signinSystemResult;
		}


		int update = siginService.update(new Date().getTime(), qrCodeDTO.getStartTime(), qrCodeDTO.getEndTime(),
				qrCodeDTO.gettId(), parseInt);
		qrCodeDTO.setHasSignin(1);
		qrCodeDTO.setStuId(parseInt);

		System.out.println("update:" + update);
		if (update == 0) {
			signinSystemResult.setSuccess(false);
			signinSystemResult.setMsg("签到超时");
			System.out.println("签到失败");
		} else {
			System.out.println("签到成功");
			signinSystemResult.setSuccess(true);
			signinSystemResult.setMsg("签到成功");
		}
		return signinSystemResult;
	}

	@RequestMapping(value = "signinList", method = RequestMethod.GET)
	public Map getSigninList(long starttime, HttpSession session) {
		Map data = null;
		try {
		System.out.println("1111111111111111111111");

			// List<Signin> signins = signinMapper.selectList(tId, stuId,
			// status);
			PageType pageType = new PageType();
			List<SigninVO> signinVOs = new ArrayList<SigninVO>();
			Teacher teacher = (Teacher) session.getAttribute("teacher");
			List<Signin> signins = signinMapper.selectByStarttimeAndTid(teacher.gettId(), starttime);
			for (Signin signin : signins) {
			SigninVO signinVO = new SigninVO();
				signinVO.setClassId(signin.getClassId().toString());
			signinVO.setName(signin.getStuName());
			signinVO.setStuId(signin.getStuId());
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

				Long signtime = signin.getSigntime();

			String time = null;
				if (signtime != null) {
					time = format.format(new Date(signtime));
			} else {
				time = "";
			}
			signinVO.setSignintime(time);

				if (signin.getStatus() == null) {
					signinVO.setStatus("否");
				} else {
					signinVO.setStatus("是");
				}
			signinVOs.add(signinVO);
		}
			data = pageType.getData();
			data.put("pageSize", 10);
			data.put("rows", signinVOs);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return data;
	}
	/**
	 * 导出学生签到excel表格
	 * @param tId
	 */
	@ApiOperation(value = "导出学生签到信息Excel表格")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "tId", value = "教师id", required = true, dataType = "Integer"),
	}
	)
	@GetMapping("export")
	public void exportSignin(Long starttime, HttpServletResponse response, HttpSession session) {
		// List<SigninVO> list = siginService.listSignin(tId);
		Teacher teacher = (Teacher) session.getAttribute("teacher");
		List<Signin> list = signinMapper.selectByStarttimeAndTid(teacher.gettId(), starttime);
		String[] titles = { "班级编号", "学生学号", "姓名", "签到时间", "签到状态" };
		ExcelUtil.exportExcel("sign", titles, list, response);
	}

	@RequestMapping(value = "/getHistory", method = RequestMethod.GET)
	public Map getHistory(Integer page, Integer rows, HttpSession session) {
		PageType pageType = new PageType();
		pageType.setPage(page);
		pageType.setRows(rows);
		Teacher teacher = (Teacher) session.getAttribute("teacher");
		List<Sst> ssts = sstMapper.selectByTid(teacher.gettId());
		List<SstDTO> sstDTOs = new ArrayList<SstDTO>();
		for (Sst sst : ssts) {
			SstDTO sstDTO = new SstDTO();
			sstDTO.setClassname(sst.getClassname());
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String format = simpleDateFormat.format(new Date(sst.getStarttime()));
			sstDTO.setStarttimeFormat(format);
			sstDTO.setStarttime(sst.getStarttime());
			sstDTOs.add(sstDTO);
		}
		Map data = pageType.getData();
		data.put("pageSize", pageType.getPage());
		data.put("rows", sstDTOs);
		return data;
		
	}

	@GetMapping("/cancel")
	public void cancle(HttpSession session) {
		session.invalidate();
	}

	@GetMapping("/getCouseInfo")
	public SigninSystemResult getCouseInfo(HttpSession session) {
		SigninSystemResult signinSystemResult = new SigninSystemResult();
		Teacher teacher = (Teacher) session.getAttribute("teacher");
		List<String> groupbyClassId = studentMapper.groupbyClassId();
		System.out.println(groupbyClassId);
		List<Course> selectByTid = courseMapper.selectByTid(teacher.gettId());
		System.out.println(selectByTid);
		Map map = new HashMap();
		map.put("classId", groupbyClassId);
		map.put("course", selectByTid);

		signinSystemResult.setData(map);
		return signinSystemResult;
	}

	@GetMapping("/signinjsp")
	public void signinjsp(long starttime, Integer tid, Long endtime, Integer classId, HttpSession session,
			HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		QRCodeDTO qrCodeDTO = (QRCodeDTO) session.getAttribute("studentInfo");
		System.out.println(starttime);
		if (qrCodeDTO == null) {
			qrCodeDTO = new QRCodeDTO();
			qrCodeDTO.setStartTime(starttime);
			qrCodeDTO.setEndTime(endtime);
			qrCodeDTO.settId(tid);
			qrCodeDTO.setClassId(classId);
			qrCodeDTO.setHasSignin(0);
			System.out.println("fist time");
		} else if (starttime != qrCodeDTO.getStartTime()) {
			qrCodeDTO.setStartTime(starttime);
			qrCodeDTO.setEndTime(endtime);
			qrCodeDTO.settId(tid);
			qrCodeDTO.setClassId(classId);
			qrCodeDTO.setHasSignin(0);
			System.out.println(starttime + "++++++" + qrCodeDTO.getStartTime());
		}
		session.setAttribute("studentInfo", qrCodeDTO);
		System.out.println("/signinjsp-->" + qrCodeDTO);
		request.getRequestDispatcher("/WEB-INF/jsp/signin.jsp").forward(request, response);
	}

}
